package com.alinu.settings.service.impl;

import com.alinu.exception.LoginException;
import com.alinu.settings.domain.User;
import com.alinu.settings.mapper.UserMapper;
import com.alinu.settings.service.UserService;
import com.alinu.utils.CommonUtil;
import com.alinu.utils.DateTimeUtil;
import com.alinu.utils.SqlSessionUtil;
import com.alinu.utils.StringUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenzuwei
 * @date 2021/3/14
 * @description 用户业务实现类
 */
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper = SqlSessionUtil.getSqlSession().getMapper(UserMapper.class);


    @Override
    public User findByActAndPwd(String account, String password, String ip) throws LoginException {
        Map<String, String> param = new HashMap<>(2);
        param.put("loginAct", account);
        param.put("loginPwd", password);

        User user = userMapper.findByActAndPwd(param);

        if (CommonUtil.isNull(user)) {
            throw new LoginException("账号密码错误");
        }

        // 验证登录信息
        String expireTime = user.getExpireTime();
        String currentTime = DateTimeUtil.getSysTime();
        if (expireTime.compareTo(currentTime) < 0) {
            throw new LoginException("账号已失效");
        }

        String lockState = user.getLockState();
        if ("0".equals(lockState)) {
            throw new LoginException("账号已锁定");
        }

        String allowIps = user.getAllowIps();
        if (StringUtil.isNotEmpty(allowIps) || allowIps.contains(ip)) {
            throw new LoginException("该ip地址受限");
        }
        return user;
    }

    /**
     * 获取用户列表信息
     *
     * @return 用户列表
     */
    @Override
    public List<User> getUserList() {

        List<User> userList = userMapper.getUserList();

        if (CommonUtil.isNotNull(userList)) {
            return userList;
        }
        return null;
    }
}
